package my.algorithms;

import my.datastructures.Node;

public class LinkedList
{
    public static Node reverseLinkedList (Node current)
    {
        Node previous = null;
        while (current != null)
        {
            Node tmpNext = current.next; //store the next node in line
            current.next = previous; // set the current node to the previous node
            previous = current; // set the previous to the current
            current = tmpNext; // set the current to the actual next node in line
        }
        
        return previous;
    }
    
    public static boolean detectLoop (Node current)
    {
    	Node ptr1 = current;
    	Node ptr2 = current;
        while (ptr1 != null && ptr2 != null)
        {
        	ptr1 = ptr1.next;
        	ptr2 = ptr2.next.next;
        	
        	if(ptr1 == ptr2)
        	{
        		return true;
        	}          
        } 
        return false;
    }
    
    public static Node middleOfLinkedList (Node current)
    {
    	Node ptr1 = current;
    	Node ptr2 = current;
        while (ptr1 != null && ptr2 != null)
        {	
        	if (ptr2.next == null)
        	{
        		break;
        	}
        	ptr1 = ptr1.next;
        	ptr2 = ptr2.next.next;          
        } 
        return ptr1;
    }
    
    
    public static void main (String [] args)
    {
    	Node n = new Node(1);
    	Node n2 = new Node(2);
    	n.next = n2;
    	n2.next = n;
    	
    	System.out.println("List has loop " + detectLoop(n));
    	
    	n.next = n2;
    	n2.next = null;
    	
    	System.out.println("List has loop " + detectLoop(n));
    	
    	Node n3 = new Node(3);
    	n2.next = n3;
    	Node n4 = new Node(4);
    	n3.next = n4;
    	Node n5 = new Node(5);
    	n4.next = n5;
    	
    	System.out.println("Middle node: " + middleOfLinkedList(n).value);
    }
    
}
